package com.sixth.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixth.annotation.PageInfoAdvice;
import com.sixth.annotation.ParameterValidation;
import com.sixth.annotation.SearchRecordAdvice;
import com.sixth.bean.*;
import com.sixth.bean.bo.AdminGoodsCreateBO;
import com.sixth.bean.common.BasePageInfo;

import com.sixth.bean.vo.*;
import com.sixth.constant.Constant;
import com.sixth.mapper.*;

import com.sixth.mapper.MarketBrandMapper;
import com.sixth.mapper.MarketCategoryMapper;
import com.sixth.mapper.MarketGoodsMapper;

import com.sixth.service.GoodsService;
import com.sixth.util.MarketInfoUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author qys
 * @Description
 * @date 2022/9/8 13:08
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketGrouponMapper marketGrouponMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketUserMapper marketUserMapper;

    // 根据类目推荐相关商品page和limit
    static Integer wxGoodsRelatedLimit = 6;
    static Integer wxGoodsRelatedPage = 1;
    /**
     *
     * @author qys
     * @date 2022/9/8 13:25
     * @param basePageInfo
     * @return Object
     */
    @PageInfoAdvice
    @Override
    public Object adminGoodsList(BasePageInfo basePageInfo, String goodsSn, Integer goodsId, String name) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setOrderByClause(basePageInfo.getSort()+ " " +basePageInfo.getOrder());
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(Constant.EXIST);
        marketGoodsExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        // 两个模糊查询
        if (goodsSn != null && !"".equals(goodsSn)) {
            criteria.andGoodsSnLike("%" + goodsSn + "%");
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        // id精准查询
        if (goodsId != null) {
            criteria.andIdEqualTo(goodsId);
        }
        return marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);



    }

    @Override
    public CatAndBrandVO catAndBrand() {
        // 查询brand表
        List<CatAndBrandInnerBrandVO> catAndBrandInnerBrandVOList = marketBrandMapper.selectAllIdAndName();
        CatAndBrandVO catAndBrandVO = new CatAndBrandVO();
        catAndBrandVO.setBrandList(catAndBrandInnerBrandVOList);
        List<CatAndBrandInnerCatVO> catAndBrandInnerCatVOList = marketCategoryMapper.selectIdAndNameAndChildrenByPid(0);
        catAndBrandVO.setCategoryList(catAndBrandInnerCatVOList);
        return catAndBrandVO;
    }


    @Transactional
    @Override
    public int adminGoodsCreate(AdminGoodsCreateBO adminGoodsCreateBO) {
        MarketGoods goods = adminGoodsCreateBO.getGoods();
        // 查询是否重名
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andNameEqualTo(goods.getName());
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        if (marketGoods != null && marketGoods.size() != 0) {
            return 611;
        }
        // 不重复就插入
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(Constant.EXIST);
        List<MarketGoodsProduct> products = adminGoodsCreateBO.getProducts();
        // 取规格中间的最小值，没有就默认为0
        BigDecimal temp = new BigDecimal(Integer.MAX_VALUE);
        for (MarketGoodsProduct product : products) {
            temp = temp.compareTo(product.getPrice()) < 0 ? temp : product.getPrice();
        }
        if (temp.compareTo(new BigDecimal(Integer.MAX_VALUE)) == 0) {
            temp = new BigDecimal(0);
        }
        goods.setRetailPrice(temp);
        try {
            marketGoodsMapper.insertSelective(goods);
            Integer goodsId = goods.getId();
            List<MarketGoodsSpecification> specifications = adminGoodsCreateBO.getSpecifications();
            for (MarketGoodsSpecification specification : specifications) {
                specification.setGoodsId(goodsId);
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specification.setDeleted(Constant.EXIST);
                marketGoodsSpecificationMapper.insertSelective(specification);
            }
            // 插入product
            for (MarketGoodsProduct product : products) {
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                product.setId(null);
                product.setGoodsId(goodsId);
                marketGoodsProductMapper.insertSelective(product);
            }
            // 插入attributes
            List<MarketGoodsAttribute> attributes = adminGoodsCreateBO.getAttributes();
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goodsId);
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(Constant.EXIST);
                marketGoodsAttributeMapper.insertSelective(attribute);
            }
        }
        catch (Exception e) {
            throw new HttpMessageNotReadableException("参数不对");
        }
        return 0;
    }

    @Override
    public AdminGoodsDetailVO adminGoodsDetail(Integer id) {
        AdminGoodsDetailVO adminGoodsDetailVO = new AdminGoodsDetailVO();
        // attributes
        List<MarketGoodsAttribute> marketGoodsAttributes = getAttributesByGoodId(id);
        adminGoodsDetailVO.setAttributes(marketGoodsAttributes);
        // goods
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
        marketGoodsExampleCriteria.andIdEqualTo(id);
        marketGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
        if (marketGoods != null && marketGoods.size() != 0) {
            adminGoodsDetailVO.setGoods(marketGoods.get(0));
        } else {
            return null;
        }
        // products
        List<MarketGoodsProduct> marketGoodsProducts = getProductsByGoodsId(id);
        adminGoodsDetailVO.setProducts(marketGoodsProducts);
        // specifications
        List<MarketGoodsSpecification> marketGoodsSpecifications = getSpecificationsByGoodsId(id);
        adminGoodsDetailVO.setSpecifications(marketGoodsSpecifications);
        // categoryIds
        MarketGoods goods = marketGoods.get(0);
        Integer categoryChildrenId = goods.getCategoryId();
        // 先查出子类目
        List<MarketCategory> marketCategories = getMarketCategoriesByCategoryId(categoryChildrenId);
        // 根据子类目pid查出父类目,排除没添加类目的情况
        if (marketCategories.size() > 0) {
            MarketCategory marketCategory = marketCategories.get(0);
            Integer categoryPid = marketCategory.getPid();
            MarketCategory marketParentCategory = marketCategoryMapper.selectByPrimaryKey(categoryPid);
            Integer parentCategoryId = marketParentCategory.getId();
            adminGoodsDetailVO.setCategoryIds(new Integer[]{parentCategoryId, categoryChildrenId});
        }

        return adminGoodsDetailVO;
    }

    private List<MarketGoodsSpecification> getSpecificationsByGoodsId(Integer goodsId) {
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria marketGoodsSpecificationExampleCriteria = marketGoodsSpecificationExample.createCriteria();
        marketGoodsSpecificationExampleCriteria.andGoodsIdEqualTo(goodsId);
        marketGoodsSpecificationExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        return marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
    }

    private List<MarketCategory> getMarketCategoriesByCategoryId(Integer categoryId) {
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        MarketCategoryExample.Criteria marketCategoryExampleCriteria = marketCategoryExample.createCriteria();
        marketCategoryExampleCriteria.andIdEqualTo(categoryId);
        marketCategoryExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        return marketCategoryMapper.selectByExample(marketCategoryExample);
    }

    private List<MarketGoodsProduct> getProductsByGoodsId(Integer goodsId) {
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria marketGoodsProductExampleCriteria = marketGoodsProductExample.createCriteria();
        marketGoodsProductExampleCriteria.andGoodsIdEqualTo(goodsId);
        marketGoodsProductExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        return marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
    }

    private List<MarketGoods> getGoodsListById(Integer goodsId) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
        marketGoodsExampleCriteria.andIdEqualTo(goodsId);
        marketGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketGoodsExampleCriteria.andIsOnSaleEqualTo(true);
        return marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
    }

    private List<MarketGoodsAttribute> getAttributesByGoodId(Integer goodsId) {
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria marketGoodsAttributeExampleCriteria = marketGoodsAttributeExample.createCriteria();
        marketGoodsAttributeExampleCriteria.andGoodsIdEqualTo(goodsId);
        marketGoodsAttributeExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        return marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
    }

    @Transactional
    @Override
    public int adminGoodsDelete(MarketGoods marketGoods) {
        Integer goodsId = marketGoods.getId();
        // 先删除goods表
        marketGoods.setUpdateTime(new Date());
        marketGoods.setDeleted(Constant.NOEXIST);
        marketGoodsMapper.updateByPrimaryKeySelective(marketGoods);
        // specification表
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria marketGoodsSpecificationExampleCriteria = marketGoodsSpecificationExample.createCriteria();
        marketGoodsSpecificationExampleCriteria.andGoodsIdEqualTo(goodsId);
        MarketGoodsSpecification marketGoodsSpecification = new MarketGoodsSpecification();
        marketGoodsSpecification.setUpdateTime(new Date());
        marketGoodsSpecification.setDeleted(Constant.NOEXIST);
        marketGoodsSpecificationMapper.updateByExampleSelective(marketGoodsSpecification, marketGoodsSpecificationExample);
        // product表
        MarketGoodsProduct marketGoodsProduct = new MarketGoodsProduct();
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria marketGoodsProductExampleCriteria = marketGoodsProductExample.createCriteria();
        marketGoodsProductExampleCriteria.andGoodsIdEqualTo(goodsId);
        marketGoodsProduct.setUpdateTime(new Date());
        marketGoodsProduct.setDeleted(Constant.NOEXIST);
        marketGoodsProductMapper.updateByExampleSelective(marketGoodsProduct, marketGoodsProductExample);
        // attribute表
        MarketGoodsAttribute marketGoodsAttribute = new MarketGoodsAttribute();
        marketGoodsAttribute.setUpdateTime(new Date());
        marketGoodsAttribute.setDeleted(Constant.NOEXIST);
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        marketGoodsAttributeMapper.updateByExampleSelective(marketGoodsAttribute, marketGoodsAttributeExample);
        return 0;
    }

    @Transactional
    @Override
    public int adminGoodsUpdate(AdminGoodsCreateBO adminGoodsCreateBO) {
        MarketGoods goods = adminGoodsCreateBO.getGoods();
        Integer goodsId = goods.getId();
        // 查询是否重名
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
        // 根据id和name查询，查询到说明没改名字
        marketGoodsExampleCriteria.andNameEqualTo(goods.getName());
        marketGoodsExampleCriteria.andIdEqualTo(goods.getId());
        List<MarketGoods> temp1 = marketGoodsMapper.selectByExample(marketGoodsExample);
        boolean flag = true;
        if (temp1 != null && temp1.size() > 0) {
            flag = false;
        }
        if (flag) {
            // 改了名字,判断是否重复
            MarketGoodsExample temp2GoodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria temp2Criteria = temp2GoodsExample.createCriteria();
            // 根据name查询，查询到说明重复
            temp2Criteria.andNameEqualTo(goods.getName());
            List<MarketGoods> temp2 = marketGoodsMapper.selectByExample(temp2GoodsExample);
            if (temp2 != null && temp2.size() > 0) {
                return 611;
            }
        }
        // 不重复就修改,只修改updateTime
        // 修改goods表
        try {
            goods.setUpdateTime(new Date());
            marketGoodsMapper.updateByPrimaryKeySelective(goods);
            // 修改specification
            List<MarketGoodsSpecification> specifications = adminGoodsCreateBO.getSpecifications();
            for (MarketGoodsSpecification specification : specifications) {
                specification.setUpdateTime(new Date());
                specification.setGoodsId(goodsId);
                marketGoodsSpecificationMapper.updateByPrimaryKey(specification);
            }
            // 修改product
            List<MarketGoodsProduct> products = adminGoodsCreateBO.getProducts();
            for (MarketGoodsProduct product : products) {
                product.setUpdateTime(new Date());
                product.setGoodsId(goodsId);
                marketGoodsProductMapper.updateByPrimaryKeySelective(product);
            }
            // 插入attributes
            List<MarketGoodsAttribute> attributes = adminGoodsCreateBO.getAttributes();
            for (MarketGoodsAttribute attribute : attributes) {
                attribute.setUpdateTime(new Date());
                attribute.setGoodsId(goodsId);
                marketGoodsAttributeMapper.updateByPrimaryKeySelective(attribute);
            }
            // 更新goods单价
            BigDecimal minPrice = marketGoodsProductMapper.selectMinPrice(goodsId);
            MarketGoods marketGoods = new MarketGoods();
            marketGoods.setId(goodsId);
            marketGoods.setRetailPrice(minPrice);
            marketGoodsMapper.updateByPrimaryKeySelective(marketGoods);
        }
        catch (Exception e) {
            throw new HttpMessageNotReadableException("参数不对");
        }

        return 0;
    }


    /**
     * @author lixinhang
     * @time 2022-09-09 10:49
     * 新增了进入微信小程序首页，查询前8条新品或者前6条热点商品的方法
     */
    @Override
    public List<WXHomeIndexGoodsVO> indexGoodsList(String s,BasePageInfo basePageInfo) {
        //PageHelper.startPage(basePageInfo.getPage(),basePageInfo.getLimit());


        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        marketGoodsExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        //判断此次是查询
        if("isNew".equals(s)){
            criteria.andIsNewEqualTo(true);
        }else{
            criteria.andIsHotEqualTo(true);
        }
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample);
        PageInfo pageInfo = new PageInfo(marketGoodsList);

        List<WXHomeIndexGoodsVO> wxHomeIndexGoodsVOList = new ArrayList<>();

        for (MarketGoods marketGoods : marketGoodsList) {
            WXHomeIndexGoodsVO wxHomeIndexGoodsVO = new WXHomeIndexGoodsVO();
            try {
                BeanUtils.copyProperties(wxHomeIndexGoodsVO,marketGoods);
            } catch (Exception e) {
                e.printStackTrace();
            }
            wxHomeIndexGoodsVOList.add(wxHomeIndexGoodsVO);
        }
        return wxHomeIndexGoodsVOList;
    }

    /**
     * @author lixinhang
     * @return
     * 查询商品数量的方法
     */
    @Override
    public Integer wxGoodsCount() {
        MarketGoodsExample example = new MarketGoodsExample();
        example.setDistinct(true);
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        Integer count = (int)marketGoodsMapper.countByExample(example);
        return count;
    }

    /**
     *
     * @author qys
     * @date 2022/9/10 14:13
     * @param id
     * @return WXGoodsCategoryVO
     */
    @Override
    public WXGoodsCategoryVO wxGoodsCategory(Integer id) {
        WXGoodsCategoryVO res = new WXGoodsCategoryVO();
        // 根据id查出对应pid，为0是父类目，查出所有子类目，选择第一个为当前类目
        // pid不为0，该类目就是当前类目，再根据pid查出其他兄弟id和父类目信息
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        // 根据id和未删除的查询
        MarketCategoryExample.Criteria marketCategoryExampleCriteria = marketCategoryExample.createCriteria();
        marketCategoryExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketCategoryExampleCriteria.andIdEqualTo(id);
        List<MarketCategory> marketCategoryList = marketCategoryMapper.selectByExample(marketCategoryExample);
        if (marketCategoryList == null || marketCategoryList.size() == 0) {
            return null;
        }
        MarketCategory marketCategory = marketCategoryList.get(0);
        // 判断是否是父类目
        if (marketCategory.getPid() == 0) {
            res.setParentCategory(marketCategory);
            MarketCategoryExample selectChildrenCategory = new MarketCategoryExample();
            MarketCategoryExample.Criteria selectChildrenCategoryCriteria = selectChildrenCategory.createCriteria();
            // 如果是父类目查询子类目
            selectChildrenCategoryCriteria.andDeletedEqualTo(Constant.EXIST);
            selectChildrenCategoryCriteria.andPidEqualTo(marketCategory.getId());
            List<MarketCategory> marketChildrenCategories = marketCategoryMapper.selectByExample(selectChildrenCategory);
            if (marketChildrenCategories == null || marketChildrenCategories.size() == 0) {
                return res;
            }
            // 分别设置，选取第一个为当前类目
            res.setCurrentCategory(marketChildrenCategories.get(0));
            res.setBrotherCategory(marketChildrenCategories);
            return res;
        }
        // pid不等于0，说明不是父类目，直接设置为当前类目
        res.setCurrentCategory(marketCategory);
        // 得到pid并查询兄弟类目，和父类目
        Integer parentId = marketCategory.getPid();
        MarketCategory parentCategory = marketCategoryMapper.selectByPrimaryKey(parentId);
        res.setParentCategory(parentCategory);
        // 查寻兄弟类目
        MarketCategoryExample brotherCategory = new MarketCategoryExample();
        MarketCategoryExample.Criteria brotherCategoryCriteria = brotherCategory.createCriteria();
        brotherCategoryCriteria.andPidEqualTo(parentId);
        brotherCategoryCriteria.andDeletedEqualTo(Constant.EXIST);
        List<MarketCategory> brotherCategories = marketCategoryMapper.selectByExample(brotherCategory);
        res.setBrotherCategory(brotherCategories);
        return res;
    }





    // @Override
    // public WXGoodsListVO wxGoodsList(Integer categoryId, Integer brandId, boolean isHot, boolean isNew, String keywords, BasePageInfo basePageInfo) {
    //     WXGoodsListVO wxGoodsListVO = new WXGoodsListVO();
    //     // 先开启分页
    //     PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
    //     // category
    //     MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
    //     marketCategoryExample.setDistinct(true);
    //     // goods
    //     MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
    //     marketGoodsExample.setDistinct(true);
    //     // 确定是否排序
    //     String sort = basePageInfo.getSort();
    //     String order = basePageInfo.getOrder();
    //     if (sort != null && order != null) {
    //         marketGoodsExample.setOrderByClause(sort + " " + order);
    //     }
    //     // 查询goods信息
    //     MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
    //     marketGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
    //     if (brandId != null) {
    //         marketGoodsExampleCriteria.andBrandIdEqualTo(brandId);
    //     }
    //     // 新品还是人气
    //     if (isHot) {
    //         marketGoodsExampleCriteria.andIsHotEqualTo(true);
    //         // 人气高的类目
    //         marketCategoryExample.setOrderByClause("sort_order desc");
    //     }
    //     if (isNew) {
    //         marketGoodsExampleCriteria.andIsNewEqualTo(true);
    //         // 新添加类目
    //         marketCategoryExample.setOrderByClause("add_time desc");
    //     }
    //     // 如果是类目id为0，搜索全部
    //     if (categoryId != null && categoryId != 0) {
    //         marketGoodsExampleCriteria.andCategoryIdEqualTo(categoryId);
    //     }
    //     // keyword
    //     if (keywords != null) {
    //         try {
    //             keywords = URLDecoder.decode(keywords, "utf-8");
    //         }
    //         catch (UnsupportedEncodingException e) {
    //             e.printStackTrace();
    //         }
    //         marketGoodsExampleCriteria.andNameLike("%" + keywords + "%");
    //     }
    //     List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
    //     // 封装goodsList
    //     wxGoodsListVO.setList(marketGoodsList);
    //     PageInfo<List<MarketGoods>> pageInfo = new PageInfo(marketGoodsList);
    //     // 封装分页信息
    //     wxGoodsListVO.setLimit(basePageInfo.getLimit());
    //     wxGoodsListVO.setPage(basePageInfo.getPage());
    //     wxGoodsListVO.setPages(pageInfo.getPages());
    //     wxGoodsListVO.setTotal(pageInfo.getTotal());
    //     // 查询按要求查找类目
    //     // TODO ： 人气类目，和新增商品类目，业务不合理
    //     PageHelper.startPage(1, basePageInfo.getLimit());
    //     MarketCategoryExample.Criteria marketCategoryExampleCriteria = marketCategoryExample.createCriteria();
    //     marketCategoryExampleCriteria.andDeletedEqualTo(Constant.EXIST);
    //     // 查询二级类目
    //     marketCategoryExampleCriteria.andPidNotEqualTo(0);
    //     List<MarketCategory> marketCategoryList = marketCategoryMapper.selectByExample(marketCategoryExample);
    //     // 封装filterCategoryList
    //     wxGoodsListVO.setFilterCategoryList(marketCategoryList);
    //     return wxGoodsListVO;
    // }

    @SearchRecordAdvice
    @Override
    public WXGoodsListVO wxGoodsList(Integer categoryId, Integer brandId, boolean isHot, boolean isNew, String keywords, BasePageInfo basePageInfo) {
        WXGoodsListVO wxGoodsListVO = new WXGoodsListVO();
        // 先开启分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        // goods
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        // 确定是否排序
        String sort = basePageInfo.getSort();
        String order = basePageInfo.getOrder();
        if (sort != null && order != null) {
            marketGoodsExample.setOrderByClause(sort + " " + order);
        }
        // 查询goods信息
        MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
        marketGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketGoodsExampleCriteria.andIsOnSaleEqualTo(true);
        if (brandId != null) {
            marketGoodsExampleCriteria.andBrandIdEqualTo(brandId);
        }
        // 新品还是人气
        if (isHot) {
            marketGoodsExampleCriteria.andIsHotEqualTo(true);
        }
        if (isNew) {
            marketGoodsExampleCriteria.andIsNewEqualTo(true);
        }
        // keyword
        if (keywords != null && !"".equals(keywords)) {
            marketGoodsExampleCriteria.andNameLike("%" + keywords + "%");
            MarketGoodsExample.Criteria or = marketGoodsExample.or();
            or.andKeywordsLike("%" + keywords + "%");
            or.andIsOnSaleEqualTo(true);
            or.andDeletedEqualTo(Constant.EXIST);
        }
        // 相应的goodsList
        List<MarketGoods> marketGoodsList = null;
        if (categoryId != null && categoryId != 0) {
            // filterCategoryList，根据查询到的goods查询相应的类目
            // 此处查询只为了得到filterCategoryList
            List<MarketGoods> marketGoods = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
            if (marketGoods == null || marketGoods.isEmpty()) {
                wxGoodsListVO.setLimit(basePageInfo.getLimit());
                wxGoodsListVO.setPages(0);
                wxGoodsListVO.setTotal(0L);
                wxGoodsListVO.setPage(0);
                return wxGoodsListVO;
            }
            List<MarketCategory> marketCategoryList = getFilterCategoryList(basePageInfo, marketGoods);
            // 封装filterCategoryList
            wxGoodsListVO.setFilterCategoryList(marketCategoryList);
            // 如果是类目id为0，搜索全部,先搜索一边goods,再传入categoryId
            if (marketGoodsExample.getOredCriteria().size() > 1) {
                // 如果oredCriteria多于一个，说明有一个是or,再传入or的categoryId
                MarketGoodsExample.Criteria or = marketGoodsExample.getOredCriteria().get(1);
                or.andCategoryIdEqualTo(categoryId);
            }
            marketGoodsExampleCriteria.andCategoryIdEqualTo(categoryId);
            PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
            marketGoodsList = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
        } else {
            marketGoodsList = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
            if (marketGoodsList == null || marketGoodsList.isEmpty()) {
                wxGoodsListVO.setLimit(basePageInfo.getLimit());
                wxGoodsListVO.setPages(0);
                wxGoodsListVO.setTotal(0L);
                wxGoodsListVO.setPage(0);
                return wxGoodsListVO;
            }
            List<MarketCategory> marketCategoryList = getFilterCategoryList(basePageInfo, marketGoodsList);
            wxGoodsListVO.setFilterCategoryList(marketCategoryList);
        }

        // 封装goodsList
        wxGoodsListVO.setList(marketGoodsList);
        PageInfo<List<MarketGoods>> pageInfo = new PageInfo(marketGoodsList);
        // 封装分页信息
        wxGoodsListVO.setLimit(basePageInfo.getLimit());
        wxGoodsListVO.setPage(basePageInfo.getPage());
        wxGoodsListVO.setPages(pageInfo.getPages());
        wxGoodsListVO.setTotal(pageInfo.getTotal());
        return wxGoodsListVO;
    }


    private List<MarketCategory> getFilterCategoryList(BasePageInfo basePageInfo, List<MarketGoods> marketGoods) {
        LinkedList<Integer> categoryIdList = new LinkedList<>();
        int goodsListSize = marketGoods.size();
        Integer pageInfoLimit = basePageInfo.getLimit();
        // 只查每页显示的商品
        int limit = pageInfoLimit < goodsListSize ? basePageInfo.getLimit() : goodsListSize;
        for (int i = 0; i < limit; i++) {
            Integer marketCategoryId = marketGoods.get(i).getCategoryId();
            categoryIdList.add(marketCategoryId);
        }
        return marketCategoryMapper.selectByIdIn(categoryIdList);
    }

    @Override
    public WXGoodsDetailVO wxGoodsDetail(Integer goodsId) {
        WXGoodsDetailVO res = new WXGoodsDetailVO();
        // 查goods信息
        List<MarketGoods> marketGoodsList = getGoodsListById(goodsId);
        if (marketGoodsList.size() ==  0) {
            return null;
        }
        res.setInfo(marketGoodsList.get(0));
        // 根据goodsId查attribute
        List<MarketGoodsAttribute> marketGoodsAttributes = getAttributesByGoodId(goodsId);
        res.setAttribute(marketGoodsAttributes);
        // 查product信息
        List<MarketGoodsProduct> marketGoodsProducts = getProductsByGoodsId(goodsId);
        res.setProductList(marketGoodsProducts);
        // 查询specification信息
        List<MarketGoodsSpecification> specificationsByGoodsId = getSpecificationsByGoodsId(goodsId);
        // 将查询到的结果转换格式
        HashMap<String, List<MarketGoodsSpecification>> specTemp = new HashMap<>();
        for (MarketGoodsSpecification specification : specificationsByGoodsId) {
            String specValue = specification.getSpecification();
            // 如果规格名第一次出现，创建该名字对应的集合
            if (specTemp.getOrDefault(specValue, null) == null) {
                LinkedList<MarketGoodsSpecification> specByName = new LinkedList<>();
                specTemp.put(specValue, specByName);
            }
            // 不是第一次出现，加入到其对应的集合中
            specTemp.get(specValue).add(specification);
        }
        List<WXGoodsDetailInnerSpecificationListVO> specificationList = new LinkedList<>();
        for (String specName : specTemp.keySet()) {
            WXGoodsDetailInnerSpecificationListVO wxGoodsDetailInnerSpecificationListVO = new WXGoodsDetailInnerSpecificationListVO();
            // 取出名字对应的集合加入返回的VO对象对应的成员变量里
            wxGoodsDetailInnerSpecificationListVO.setName(specName);
            wxGoodsDetailInnerSpecificationListVO.setValueList(specTemp.get(specName));
            specificationList.add(wxGoodsDetailInnerSpecificationListVO);
        }
        res.setSpecificationList(specificationList);
        // 查询issue
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        MarketIssueExample.Criteria marketIssueExampleCriteria = marketIssueExample.createCriteria();
        marketIssueExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        List<IssueListInnerVO> issueListInnerVOS = marketIssueMapper.selectByExample(marketIssueExample);
        res.setIssue(issueListInnerVOS);
        // 查询groupon
        MarketGrouponRulesExample marketGrouponRulesExample = new MarketGrouponRulesExample();
        MarketGrouponRulesExample.Criteria marketGrouponRulesExampleCriteria = marketGrouponRulesExample.createCriteria();
        marketGrouponRulesExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketGrouponRulesExampleCriteria.andGoodsIdEqualTo(goodsId);
        List<MarketGrouponRules> marketGrouponRules = marketGrouponRulesMapper.selectByExample(marketGrouponRulesExample);
        res.setGroupon(marketGrouponRules);
        // 查询brand
        MarketGoods marketGoods = marketGoodsList.get(0);
        Integer brandId = marketGoods.getBrandId();
        if (brandId != null) {
            MarketBrandExample marketBrandExample = new MarketBrandExample();
            MarketBrandExample.Criteria marketBrandExampleCriteria = marketBrandExample.createCriteria();
            marketBrandExampleCriteria.andDeletedEqualTo(Constant.EXIST);
            marketBrandExampleCriteria.andIdEqualTo(brandId);
            List<MarketBrand> marketBrands = marketBrandMapper.selectByExample(marketBrandExample);
            if (marketBrands.size() != 0) {
                res.setBrand(marketBrands.get(0));
            }
        }
        // 查询comment
        MarketCommentExample marketCommentExample = new MarketCommentExample();
        MarketCommentExample.Criteria marketCommentExampleCriteria = marketCommentExample.createCriteria();
        marketCommentExampleCriteria.andValueIdEqualTo(goodsId);
        marketCommentExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        List<MarketComment> marketComments = marketCommentMapper.selectByExample(marketCommentExample);
        // 转换格式
        WXGoodsDetailInnerCommentVO wxGoodsDetailInnerCommentVO = new WXGoodsDetailInnerCommentVO();
        wxGoodsDetailInnerCommentVO.setCount(marketComments.size());
        LinkedList<WXGoodsDetailInnerCommentInnerDataVO> wxGoodsDetailInnerCommentInnerDataVOS = new LinkedList<>();
        int size = 2 > marketComments.size() ? marketComments.size() : 2;
        for (int i = 0; i < size; i++) {
            WXGoodsDetailInnerCommentInnerDataVO wxGoodsDetailInnerCommentInnerDataVO = new WXGoodsDetailInnerCommentInnerDataVO();
            MarketComment marketComment = marketComments.get(i);
            wxGoodsDetailInnerCommentInnerDataVO.setAddTime(marketComment.getAddTime());
            wxGoodsDetailInnerCommentInnerDataVO.setAdminContent(marketComment.getAdminContent());
            wxGoodsDetailInnerCommentInnerDataVO.setContent(marketComment.getContent());
            wxGoodsDetailInnerCommentInnerDataVO.setPicList(marketComment.getPicUrls());
            wxGoodsDetailInnerCommentInnerDataVO.setId(marketComment.getId());
            Integer userId = marketComment.getUserId();
            MarketUser marketUser = marketUserMapper.selectByPrimaryKey(userId);
            wxGoodsDetailInnerCommentInnerDataVO.setAvatar(marketUser.getAvatar());
            wxGoodsDetailInnerCommentInnerDataVO.setNickname(marketUser.getNickname());
            wxGoodsDetailInnerCommentInnerDataVOS.add(wxGoodsDetailInnerCommentInnerDataVO);
        }
        wxGoodsDetailInnerCommentVO.setData(wxGoodsDetailInnerCommentInnerDataVOS);
        res.setComment(wxGoodsDetailInnerCommentVO);
        // 分享
        String shareUrl = marketGoods.getShareUrl();
        if (shareUrl != null) {
            res.setShare(true);
            res.setShareImage(shareUrl);
        }
        // TODO : 获得userId看是否已经评收藏和专题
        MarketUser marketUser = MarketInfoUtil.getMarketUser();
        if (marketUser != null) {
            Integer userId = marketUser.getId();
            MarketCollectExample marketCollectExample = new MarketCollectExample();
            MarketCollectExample.Criteria marketCollectExampleCriteria = marketCollectExample.createCriteria();
            marketCollectExampleCriteria.andDeletedEqualTo(Constant.EXIST);
            marketCollectExampleCriteria.andUserIdEqualTo(userId);
            marketCollectExampleCriteria.andValueIdEqualTo(goodsId);
            marketCollectExampleCriteria.andTypeEqualTo((byte)0);
            List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(marketCollectExample);
            if (marketCollects.size() == 0) {
                res.setUserHasCollect(0);
            } else {
                res.setUserHasCollect(1);
            }
            if (res.getUserHasCollect() == null) {
                res.setUserHasCollect(0);
            }
        }
        return res;
    }

    @Override
    public WXGoodsRelatedVO wxGoodsRelated(Integer goodsId) {
        // 根据一级类目查询相似货物
        List<MarketGoods> goodsListById = getGoodsListById(goodsId);
        if (goodsListById.size() == 0) {
            return null;
        }
        // 先获得二级类目id
        MarketGoods marketGoods = goodsListById.get(0);
        Integer childrenId = marketGoods.getCategoryId();
        if (childrenId == null) {
            return null;
        }
        // // 查询二级类目
        // List<MarketCategory> childrenCategories = getMarketCategoriesByCategoryId(childrenId);
        // if (childrenCategories.size() == 0) {
        //     return null;
        // }
        // 获得一级类目
        // MarketCategory childrenCategory = childrenCategories.get(0);
        // Integer parentId = childrenCategory.getPid();
        // List<MarketCategory> marketCategoriesByCategoryId = getMarketCategoriesByCategoryId(parentId);
        // if (marketCategoriesByCategoryId.size() == 0) {
        //     return null;
        // }
        // TODO: 写死了只显示第一页，六个商品，且只根据二级类目查询
        PageHelper.startPage(wxGoodsRelatedPage, wxGoodsRelatedLimit);
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        MarketGoodsExample.Criteria marketGoodsExampleCriteria = marketGoodsExample.createCriteria();
        marketGoodsExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketGoodsExampleCriteria.andIsOnSaleEqualTo(true);
        // 根据二级类目id查询，排除掉同一件货物的情况
        marketGoodsExampleCriteria.andCategoryIdEqualTo(childrenId);
        marketGoodsExampleCriteria.andIdNotEqualTo(goodsId);
        List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
        WXGoodsRelatedVO res = new WXGoodsRelatedVO();
        PageInfo pageInfo = new PageInfo(marketGoodsList);
        res.setLimit(wxGoodsRelatedLimit);
        res.setPage(wxGoodsRelatedPage);
        res.setPages(pageInfo.getPages());
        res.setTotal(pageInfo.getTotal());
        // 再转化goods的格式
        LinkedList<WXGoodsRelatedInnerGoodsVO> temp = new LinkedList<>();
        for (MarketGoods goods : marketGoodsList) {
            WXGoodsRelatedInnerGoodsVO wxGoodsRelatedInnerGoodsVO = new WXGoodsRelatedInnerGoodsVO();
            wxGoodsRelatedInnerGoodsVO.setBrief(goods.getBrief());
            wxGoodsRelatedInnerGoodsVO.setCounterPrice(goods.getCounterPrice());
            wxGoodsRelatedInnerGoodsVO.setRetailPrice(goods.getRetailPrice());
            wxGoodsRelatedInnerGoodsVO.setId(goods.getId());
            wxGoodsRelatedInnerGoodsVO.setHot(goods.getIsHot());
            wxGoodsRelatedInnerGoodsVO.setNew(goods.getIsNew());
            wxGoodsRelatedInnerGoodsVO.setName(goods.getName());
            wxGoodsRelatedInnerGoodsVO.setPicUrl(goods.getPicUrl());
            temp.add(wxGoodsRelatedInnerGoodsVO);
        }
        res.setList(temp);
        return res;
    }
}
